<!-- subpkg_archive/form/index.vue -->
<script setup>
	import { ref } from 'vue'
	import { addPatientApi, patientDetailApi, updatePatientApi } from '@/services/patient'
	import { onLoad } from '@dcloudio/uni-app'
	const isDefault = ref([0])
	const form = ref(null)
	const formData = ref({
	  name: '',
	  idCard: '',
	  gender: 1,
	  defaultFlag: 1,
	})
	const formRules = {
	    name: {
	      rules: [
	        { required: true, errorMessage: '请填写患者姓名' },
	        {
	          pattern: '^[\u4e00-\u9fa5]{2,5}$',
	          errorMessage: '患者姓名为2-5位中文',
	        },
	      ],
	    },
	    idCard: {
	      rules: [
	        { required: true, errorMessage: '请输入身份证号' },
	        {
	          pattern:
	            '^[1-9]\\d{5}(?:18|19|20)\\d{2}(?:0[1-9]|10|11|12)(?:0[1-9]|[1-2]\\d|30|31)\\d{3}[\\dXx]$',
	          errorMessage: '身份证号格式不正确',
	        },
	      ],
	    },
	    gender: {
	      rules: [
	        { required: true, errorMessage: '请勾选患者性别' },
			{
				validateFunction: (rule, value, data, callback) => {
					if (data.idCard.slice(16, 17) % 2 !== value) {
						callback('勾选的性别和身份证号不一致')
					}
					return true
				}
			}
	      ],
	    },
	  }
	// 是否为默认就诊人
	
	const props = defineProps()
	const ptId = ref('')
	onLoad(({ id }) => {
		ptId.value = id
		getPtDetail()
	})
	
	function onSwitchChange(ev) {
	  console.log(ev, 'ev');
	  // 是否设置为默认就诊患人
	  formData.value.defaultFlag = ev.detail.value ? 1 : 0
	}
	
	async function save () {
		try {
			const flag = await form.value.validate()
			ptId.value ? editData() : addData()
		} catch (error) {
			console.log(error, 'error');
			//TODO handle the exception
		}
	}
	async function addData () {
		try {
			const { code, message } = await addPatientApi(formData.value)
			if (code !== 10000) return uni.utils.toast(message)
			// 跳转到患者页面
			uni.navigateBack()
		} catch (error) {
			console.log(error, 'error');
		}
	}
	async function editData () {
		try {
			const { code, message } = await updatePatientApi(formData.value)
			if (code !== 10000) return uni.utils.toast(message)
			// 跳转到患者页面
			uni.navigateBack()
		} catch (error) {
			console.log(error, 'error');
		}
	}
	// 获取患者详情
	async function getPtDetail () {
		try {
			if (!ptId.value) return
			// 有id，修改标题
			uni.setNavigationBarTitle({
				title: '编辑患者'
			})
			const 
			{ code, message, data: {age, genderValue, ...rest}}
			= await patientDetailApi(ptId.value);
			if (code !== 10000) return uni.utils.toast(message)
			// 跳转到患者页面
			formData.value = rest
		} catch (error) {
			console.log(error, 'error');
			//TODO handle the exception
		}
	}
</script>

<template>
  <scroll-page>
    <view class="archive-page">
      <uni-forms 
		  border 
		  label-width="220rpx" 
		  ref="form"
		  :model="formData"
		  :rules="formRules"
	  >
        <uni-forms-item label="患者姓名" name="name">
          <uni-easyinput
            placeholder-style="color: #C3C3C5; font-size: 32rpx"
            :styles="{ color: '#121826' }"
            :input-border="false"
            :clearable="false"
            placeholder="请填写真实姓名"
			v-model="formData.name"
          />
        </uni-forms-item>

        <uni-forms-item label="患者身份证号" name="idCard">
          <uni-easyinput
            placeholder-style="color: #C3C3C5; font-size: 32rpx"
            :styles="{ color: '#121826' }"
            :input-border="false"
            :clearable="false"
            placeholder="请填写身份证号"
			v-model="formData.idCard"
          />
        </uni-forms-item>

        <uni-forms-item label="患者性别" name="gender">
          <uni-data-checkbox
            selectedColor="#16C2A3"
            :localdata="[
              { text: '男', value: 1 },
              { text: '女', value: 0 },
            ]"
			v-model="formData.gender"
          />
        </uni-forms-item>

        <uni-forms-item label="默认就诊人" name="">
          <view class="uni-switch">
            <switch 
				color="#20c6b2" 
				style="transform: scale(0.7)" 
				@change="onSwitchChange"
				:checked="formData.defaultFlag === 1"
			/>
          </view>

        </uni-forms-item>

        <button class="uni-button" @click="save">保存</button>

      </uni-forms>

    </view>

  </scroll-page>

</template>

<style lang="scss">
  @import './index.scss';
</style>
